﻿using SharpDX;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
using System.Linq;
using Device = SharpDX.Direct3D11.Device;
using Buffer = SharpDX.Direct3D11.Buffer;
using MapFlags = SharpDX.Direct3D11.MapFlags;

namespace MikadoShooter
{
    public static partial class GameHelper
    {
        public static void Render(Device device, Buffer buffer, int stride, PrimitiveTopology primitiveTopology, params DrawBase[] drawBase)
        {
            int vertexCount = 0;
            device.ImmediateContext.InputAssembler.PrimitiveTopology = primitiveTopology;
            DataBox box = device.ImmediateContext.MapSubresource(buffer, 0, MapMode.WriteDiscard, MapFlags.None);

            //Write all vertex from drawBase to the DataBox IntPointer..
            foreach (var data in drawBase.Where(data => data.Length > 0))
            {
                Utilities.Write(Utilities.IntPtrAdd(box.DataPointer, vertexCount * stride), data.Data, 0, data.Length * 2);
                vertexCount += data.Length;
            }
            device.ImmediateContext.UnmapSubresource(buffer, 0);

            device.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(buffer, stride, 0));
            device.ImmediateContext.Draw(vertexCount, 0);
        }

        public static void RenderBuffer(Device device, Buffer buffer, int stride)
        {
            device.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
            device.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(buffer, stride, 0));
            device.ImmediateContext.Draw(4, 0);
        }
    }
}